'use client'

import { DeletePostProps } from '@/lib/types'
import React, { useState } from 'react'
import { Button } from '../ui/button'
import { Trash2 } from 'lucide-react'
import { deletePost } from '@/actions/post-actions'
import { toast } from 'sonner'
import { useRouter } from 'next/navigation'

export default function DeletePost({ postId }: DeletePostProps) {
    const router = useRouter()
    const [isDeleteing, setIsDeleteing] = useState(false)

    async function handleDelete(postId: number) {
        setIsDeleteing(true)
        try {
            const res = await deletePost(postId)
            toast(res.message)
            if (res.success) {
                router.push('/')
                router.refresh()
            }
        } catch (e) {
            toast('Post deletion failed')
        } finally {
            setIsDeleteing(false)
        }
    }

    return <Button onClick={() => handleDelete(postId)} variant={'destructive'} size={'sm'} disabled={isDeleteing}>
        <Trash2 className='h-4 w-4 mr-2' />
        {isDeleteing ? 'Deleting' : 'Delete'}
    </Button>
}
